<?php

// basecamp
function rad_init( )
{
//	define( '___dirs',	'classes, controllers, models, views, helpers', 1 );
	define( '__core',	pathinfo( __FILE__, PATHINFO_DIRNAME ).'/', 1 );
	
	$app = realpath( __core.'../application/' );
	if( !file_exists( $app ) )
		$app = realpath( __core.'../exts/' ); // back-compatibility
	define( '__apps',	$app.'/', 1 );
	
	define( '__site',	realpath( __core.'../site/' ).'/', 1 );
	define( '__exts',	__apps, 1 ); // back-compatibility
	
	define( 'BASEPATH',		__core );
	define( 'APPPATH',		__apps );
	define( 'SITEPATH',		__site );
//	define( 'APPLICATION',	__apps );
	
	if( !defined( 'ROOT' ) )
	define( 'root',		pathinfo( $_SERVER['SCRIPT_FILENAME'], PATHINFO_DIRNAME ).'/', 1 );
	
	define( 'ROOTPATH',		ROOT );
	
	define( 'CONSOLE', PHP_SAPI == 'cli' || (!isset($_SERVER['DOCUMENT_ROOT']) && !isset($_SERVER['REQUEST_URI'])) );
	
	define( 'EXT', '.php' );

	/*
	 * Temporary helper pre-loaders
	 */
	load_helpers('array','tools','file','http','form','url','nonce','language','html','mvc');
	rad_loaded('helpers');

	config::instance();
	rad_loaded('config');

}

function rad_loaded($is=null)
{
	static $loaded;
	if(!is_array($loaded))
		$loaded = array('helpers'=>0,'config'=>0);

	if(!is_null($is)&&isset($loaded[$is]))
		$loaded[$is]++;

	return array_product($loaded);
}

function fetch_file($where, $what, $postfix = '', $ext = EXT)
{
	if ($ext[0]!='.')
		$ext = '.' . $ext;

    $postfix = (array)($postfix);
    $where = (array)($where);
	$what = (array)($what);
	
    foreach($where as $path) {
        foreach($what as $file) {
            foreach($postfix as $p) {
                $filenames = array(
                    $path . $file . $p . $ext,
                    $path . $file
                    );
				
                foreach($filenames as $filename) {
                    if( is_readable($filename) && is_file($filename) )
                        return $filename;
                }
            }
        }
    }
	
    return false;
}

function load_standard_file($name, $types)
{
	$definedTypes = array(
		'class' => array( 'path' => 'classes', 'postfix' => '' ),
		'model' => array( 'path' => 'models', 'postfix' => '' ),
		'controller' => array( 'path' => 'controllers', 'postfix' => '' ),
		'library' => array( 'path' => 'libraries', 'postfix' => '' ),
		'helper' => array( 'path' => 'helpers', 'postfix' => '_helper' ),
		);
	
	$types = (array)($types);
	$base_paths = rad_base_paths();

	foreach( $types as $type )
	{
		if( !isset( $definedTypes[$type] ) )
			throw new Exception( 'unknown file type "'.$type.'"' );
		
		$type = $definedTypes[$type];
		$paths = array(); foreach( $base_paths as $path ) $paths[] = $path . $type['path'] . '/';

		$filename = fetch_file( $paths, array( $name, strtolower( $name ) ), $type['postfix'] );
		
	    if($filename !== false)
		{
    	    require_once($filename);
			return true;
		}
	}
}

function fetch_special_file($file, $path = '/')
{
	$paths = (array)($path);
	$where = array( );

	foreach( $paths as $path )
		foreach( rad_base_paths() as $basepath )
			$where[] = $basepath . $path . '/';

	$files = (array)($file);
	foreach($files as $k => $file)
		if(pathinfo($file,PATHINFO_EXTENSION)=='')
			$files[$k] .= EXT;
	foreach($files as $file)
		$files[] = strtolower( $file );
	$files = array_unique($files);
	
	return fetch_file( $where, $files );
}

function load_special_file($file, $path = '/')
{
	$filename = fetch_special_file($file, $path);

	if($filename === false)
		return false;

	require_once($filename);
	return true;
}

function load_helper($helper) {
	return load_standard_file($helper, 'helper');
}
function load_helpers(/*...*/) {
	$r = 0;
	foreach(func_get_args() as $helper)
		$r += load_standard_file($helper, 'helper');
	return $r;
}

function rad_modules() {

	if(!rad_loaded())
		return array();
	
	static $modules;

	if(!is_null($modules))
		return $modules;

	$raw_modules = config::instance()->modules;
	$modules = array();
	
	if(!$raw_modules)
		return $modules;

	foreach(explode(' ',$raw_modules) as $module)
	{
		if(strpos($module,'~')!==false)
			continue;
		
		$module = trim($module);
		$module_tag = preg_replace('@[^a-z]@i','',$module);
		$module_path = ROOTPATH . $module . '/';
		if( !file_exists( $module_path ) || !is_dir( $module_path ) || !is_readable( $module_path ) )
			die( sprintf(__('Module "%s" not exists.'),$module) );
		
		define( strtoupper( $module_tag ) . 'PATH', $module_path );
		$modules[] = array(
			'name' => $module,
			'tag' => $module_tag,
			'path' => $module_path,
			);
	}

	return $modules;
}

function rad_base_paths($sub = null) {

	if($sub)
		$sub = trim($sub,'/') . '/';

	$r = array();

	$r[] = APPPATH . $sub;
	
	foreach( rad_modules() as $module )
		$r[] = $module['path'] . $sub;
	
	$r[] = BASEPATH . $sub;

	return $r;
}

function __autoload( $class )
{
	$fullclass = $class.'.php';
	
	// controllers
	if( strpos( $fullclass, 'controller.php' ) != 0 )
	{
		@define( 'yo',1 );
		$fullclass = ( strpos( strtolower($fullclass), 'admin_controller.p' ) != 0 )
			? 'admin/'.str_ireplace( '_admin_controller.php', '', $fullclass )
			: str_ireplace( '_controller.php', '', $fullclass );
		
		if( load_standard_file( $fullclass, 'controller' ) ) return;
	}
	
	if( load_standard_file( $class, array( 'class', 'model' ) ) ) return;
	
	return @include_once( str_replace( '_', '/', $class.'.php' ) );
}

// for error showing
register_shutdown_function( create_function( '', "singleton::destroy( 'response' );" ) );

// load defines and so on)
rad_init( );


